/*
 Copyright 2014 Alexander V. Nikulin
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
	
 	http://www.apache.org/licenses/LICENSE-2.0
	
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/
package ru.avn.adf;

/**
 * @author Alexander V. Nikulin
 */
public class PayloadProcessorInvoker {

	private PayloadProcessor<?> payloadProcessor;
	private PayloadBodyExtractor payloadExtractor;
		
	private PayloadProcessorInvoker(Builder builder) {
		this.payloadProcessor = builder.payloadProcessor;
		this.payloadExtractor = builder.payloadExtractor;
	}
	
	public static Builder newBuilder() {
		return new Builder();
	}
	
	
	public void invoke(final Object object, AdfExecutorContext context) throws PayloadProcessorException {
		payloadProcessor.process(new Payload() {
			
			private Object body = null;
			
			@Override
			public void updateBody(Object body) {
				payloadExtractor.load(body, object);
			}
			
			@SuppressWarnings("unchecked")
			@Override
			public <T> T getBody() {
				if (body == null) {
					body = payloadExtractor.extract(object);
				}
				return (T) body;
			}

			@Override
			public boolean isAssignable(Class<?> classType) {
				Object body = getBody();
				Class<?> bodyClass = body == null ? null : body.getClass();
				return classType.isAssignableFrom(bodyClass);
			}
						
		}, context);
		
	}
	
	
	public static class Builder {
		private PayloadProcessor<?> payloadProcessor;
		private PayloadBodyExtractor payloadExtractor;
				
		public Builder processor(PayloadProcessor<?> payloadProcessor) {
			this.payloadProcessor = payloadProcessor;
			return this;
		}
		
		public Builder extractor(PayloadBodyExtractor payloadExtractor) {
			this.payloadExtractor = payloadExtractor;
			return this;
		}
			
		public PayloadProcessorInvoker build() {
			if (payloadExtractor == null || payloadProcessor == null) {
				throw new IllegalStateException("payloadExtractor is null or payloadHandler is null");
			}
			
			return new PayloadProcessorInvoker(this);
		}
	}
	
}
